<template>
  <div>
    <div class="warp-box  clearfix">
      <div class="warp-con">
        <div class="search">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="模块">
              <el-select v-model="searchFrom.module" placeholder="请选择" class="width150">
                <el-option
                  v-for="(item, j) in sexList"
                  :key="j"
                  :label="item.label"
                  :value="item.val">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="操作人">
              <el-select v-model="searchFrom.operatorId" placeholder="请选择" class="width150">
                <el-option
                  v-for="(item, j) in sexList"
                  :key="j"
                  :label="item.label"
                  :value="item.val">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间段">
              <el-date-picker
                class="width300"
                v-model="selectTime"
                type="datetimerange"
                :picker-options="pickerOptions2"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
              </el-date-picker>
              <!--<el-input-->
              <!--v-model="searchFrom.name"-->
              <!--@keyup.enter.native="getBackupList"-->
              <!--auto-complete="off">-->
              <!--<i-->
              <!--class="el-icon-close el-input__icon"-->
              <!--slot="suffix"-->
              <!--@click="searchFrom.name = ''">-->
              <!--</i>-->
              <!--</el-input>-->
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getLogList">查询</el-button>
            </el-form-item>
            <!--<el-form-item>-->
            <!--<el-button type="primary"  @click="addUserDialog">新增</el-button>-->
            <!--</el-form-item>-->
            <!-- <el-form-item>
              <el-button type="primary"  @click="deleteSamplePlot()">批量删除</el-button>
            </el-form-item> -->
          </el-form>
        </div>
        <div class="forms">
          <el-table
            ref="multipleTable"
            border
            stripe
            :data="tableData"
            :tooltip-effect="'dark'"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <!--<el-table-column-->
            <!--type="selection">-->
            <!--</el-table-column>-->
            <el-table-column
              prop="operateTime"
              show-overflow-tooltip
              label="时间">
            </el-table-column>
            <el-table-column
              prop="operation"
              show-overflow-tooltip
              label="操作对象">
            </el-table-column>
            <el-table-column
              prop="operatorId"
              show-overflow-tooltip
              label="主机">
            </el-table-column>
            <el-table-column
              prop="operator"
              show-overflow-tooltip
              label="操作人">
            </el-table-column>
            <!--<el-table-column-->
            <!--prop="Sex"-->
            <!--show-overflow-tooltip-->
            <!--label="性别">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.Sex | sexFilter}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <!--<el-table-column-->
            <!--show-overflow-tooltip-->
            <!--label="创建时间">-->
            <!--<template slot-scope="scope">-->
            <!--{{scope.row.CreateTime | time-formater-has-hour}}-->
            <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column
              label="操作"
              align="center"
              width="140">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="详情" placement="top">
                  <el-button @click="updateDetail(scope.row)" type="text" title="修改">
                    <span class="pointer">修改</span>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination v-if="tableData && tableData.length && totalNum > 10"
                         @current-change="pager"
                         :current-Page="pageIndex"
                         :page-size="pageSize"
                         layout="total, prev, pager, next, jumper"
                         :total="totalNum">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :title="detailEditType == 'edit' ? '系统日志-详情' : '添加用户'" :width="'40%'" :visible.sync="dialogFormVisible">
      <el-form labelPosition='left' class="select-form" :rules="rulesAdd" ref="ruleAddForm" :inline="true"
               :model="addForm">
        <el-form-item class="paddingTB10" label="时间" prop="name" label-width="140px">
          <span v-show="detailEditType == 'edit'">{{addForm.operateTime}}</span>
        </el-form-item>
        <el-form-item class="paddingTB10" label="操作模块" label-width="140px">
          <span v-show="detailEditType == 'edit'">{{addForm.module}}</span>
        </el-form-item>
        <el-form-item class="paddingTB10" label="登录信息" label-width="140px">
          <span v-show="detailEditType == 'edit'">{{addForm.operatorId}}</span>
        </el-form-item>
        <el-form-item class="paddingTB10" label="请求地址" label-width="140px">
          <span v-show="detailEditType == 'edit'">{{addForm.url}}</span>
        </el-form-item>
        <el-form-item class="paddingTB10" label="请求状态" label-width="140px">
          <span v-show="detailEditType == 'edit'">{{addForm.content}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--<el-button v-if="detailEditType == 'edit'" type="primary" @click="updateDetailSubmit('ruleAddForm')">修 改-->
        <!--</el-button>-->
        <!--<el-button v-else type="primary" @click="addUser('ruleAddForm')">添 加</el-button>-->
        <el-button type="primary" @click="dialogFormVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import systemApi from '@/api/systemApi'

export default {
  // name: '订单列表',
  data () {
    var validateAccount = (rule, value, callback) => {
      let uPattern = /^[a-zA-Z0-9]{6,16}$/ // 用户名正则，6到16位（字母，数字，下划线）
      if (!value) {
        return callback(new Error('账户名不能为空！'))
      } else {
        if (uPattern.test(value) === false) {
          callback(new Error('6到16位（字母，数字，下划线）'))
        } else {
          callback()
        }
      }
    }
    var validatePass = (rule, value, callback) => {
      let pPattern = /^[a-zA-Z0-9]{6,16}$/ // 密码正则，6到16位（字母，数字，下划线）
      if (value === '') {
        callback(new Error('密码不能为空！'))
      } else {
        if (pPattern.test(value) === false) {
          callback(new Error('6到16位（字母，数字，下划线）'))
        } else {
          callback()
        }
      }
    }
    var validateRePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.Password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      selectTime: '',
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
          // },
          //   {
          //   text: '最近一个月',
          //   onClick(picker) {
          //     const end = new Date();
          //     const start = new Date();
          //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          //     picker.$emit('pick', [start, end]);
          //   }
          // }, {
          //   text: '最近三个月',
          //   onClick(picker) {
          //     const end = new Date();
          //     const start = new Date();
          //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          //     picker.$emit('pick', [start, end]);
          //   }
        }]
      },
      searchFrom: {
        module: '',
        timeRange: '',
        operatorId: ''
      },
      tableData: [],
      pageIndex: 1,
      pageSize: 10,
      totalNum: 0,
      dialogFormVisible: false,
      detailEditType: 'detail', // 'edit'
      userDetail: {
        Name: ''
      },
      initAddForm: {
        operateTime: '',
        module: '',
        operatorId: '',
        content: '',
        url: ''
      },
      addForm: {},
      sexList: [
        {label: '未知', val: 0},
        {label: '男', val: 1},
        {label: '女', val: 2}
      ],
      rulesAdd: {
        value: [
          {required: true, message: '请填写值', trigger: 'blur'}
        ],
        UserName: [
          {required: true, message: '账户真实姓名', trigger: 'blur'}
        ],
        Account: [
          {validator: validateAccount, required: true, trigger: 'blur'}
        ],
        Password: [
          {validator: validatePass, required: true, trigger: 'blur'}
        ],
        RePassword: [
          {validator: validateRePass, required: true, trigger: 'blur'}
        ]
      },
      plantSelection: [],
      deletIds: []
    }
  },
  components: {},
  filters: {
    sexFilter (val) {
      let str
      let vals = val + ''
      switch (vals) {
        case '1':
          str = '男'
          break
        case '2':
          str = '女'
          break
        default:
          str = '未知'
      }
      return str
    }
  },
  created () {
    this.addForm = Object.assign({}, this.initAddForm)
    this.getLogList()
  },
  mounted () {
  },
  methods: {
    getLogList () {
      systemApi.getLogList({
        PageIndex: this.pageIndex,
        pageSize: this.pageSize,
        module: this.searchFrom.module,
        timeRange: this.searchFrom.timeRange,
        operatorId: this.searchFrom.operatorId
      }).then((res) => {
        if (res.data.messageType === 0) {
          console.log(res)
          let result = res.data.result
          this.tableData = result.rows
          // this.totalNum = result.Records
        } else {
          this.tableData = []
        }
      })
    },
    addUserDialog () {
      this.detailEditType = 'add'
      this.dialogFormVisible = true
      this.addForm = Object.assign({}, this.initAddForm)
    },
    addUser (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = Object.assign({
            UserID: '',
            ProtectID: '01',
            UserName: '',
            EndemicSpecies: '',
            ProtectedArea: ''
          }, this.addForm)
          systemApi.addUser(params).then((res) => {
            if (res.data.MessageType === 0) {
              this.$notify({
                title: '消息',
                message: ('添加成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              this.dialogFormVisible = false
              this.addForm = {
                ProtectedArea: '',
                UserName: '',
                EndemicSpecies: false
              }
              this.getLogList()
            }
          })
        } else {
          return false
        }
      })
    },
    updateDetailSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = this.addForm
          systemApi.updateUser(params).then((res) => {
            if (res.data.MessageType === 0) {
              this.addForm = Object.assign({}, this.initAddForm)
              this.$notify({
                title: '消息',
                message: ('操作成功!'),
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              this.dialogFormVisible = false
            }
          })
        } else {
          return false
        }
      })
    },
    handleSelectionChange (val) {
      this.plantSelection = val
      let ids = []
      this.plantSelection.forEach((n) => {
        ids.push(n.ID)
      })
      this.deletIds = ids
    },
    // 当前页
    pager (val) {
      this.pageIndex = val
      this.getLogList()
    },
    updateDetail (row) {
      this.dialogFormVisible = true
      this.detailEditType = 'edit'
      this.addForm = Object.assign({}, row)
      this.addForm.RePassword = this.addForm.Password
      let params = row.id
      systemApi.getLogDetail(params).then((res) => {
        console.log(res)
        if (res.data.messageType === 0) {
          console.log(res.data.result.content)
          this.addForm = Object.assign({}, this.initAddForm)
          this.addForm.operateTime = row.operateTime
          this.addForm.module = row.module
          this.addForm.operatorId = row.operatorId
          this.addForm.content = res.data.result.content
          this.addForm.url = res.data.result.url
        }
      })
    },
    deleteUser (row) {
      let tips = ''
      let params = {}
      if (row) {
        tips = `此操作将删除: ${row.UserName}, 是否继续?`
        params.UserID = row.UserID
      } else {
        return
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        systemApi.deleteUser(params).then((res) => {
          if (res.data.MessageType === 0) {
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
            this.getLogList()
          }
        })
      }).catch((error) => {
        console.log(error)
      })
    }
  }
}
</script>
<style lang="less" scoped>

  .f-g-sd1 {
    position: relative;
    float: left;
    width: 95px;
    margin-right: -95px;
  }

  .f-g-mn1 {
    float: right;
    width: 100%;
  }

  .f-g-mn1c {
    margin-left: 100px;
  }

  .detail-body {
    color: rgba(250, 250, 250, 0.9);
    &::after {
      content: '';
      display: block;
      visibility: hidden;
      height: 0;
      clear: both;
    }
  }

  .item-inline {
    width: 50%;
    float: left;
    margin-bottom: 20px;
    .item-name {
      display: inline-block;
    }
    .item-context {
      display: inline-block;
    }
  }

  .no-data {
    text-align: center;
    font-size: 14px;
    .tips {
      padding: 20px 0px;
      color: #666;
    }
  }

  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }

  .marginR20 {
    margin-right: 20px;
    float: right;
  }
  .width150{
    width: 150px;
  }
  .width300{
    width: 300px;
  }
</style>
<style lang="less">
  /**
   * 修改样式   覆盖默认的饿了么全局样式
   */
  .el-form-item__label {
    padding: 0 20px 0 0 !important;
  }
</style>
